﻿// See https://aka.ms/new-console-template for more information
using Newtonsoft.Json;
using SocketService;
using System.ComponentModel;
using System.Diagnostics;
using System.Net;
using System.Security.Principal;

//if (!IsRunAsAdministrator())
//{
//    // 如果当前程序没有管理员权限，重新启动并要求管理员权限
//    RestartAsAdministrator();
//    return;
//}
Console.WriteLine("Socket要以管理员身份运行！！！");

IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in ipEntry.AddressList)
{
    Console.WriteLine("IP Address: " + ip.ToString());
}

string prefix = $"http://192.168.51.57:9528/wpf/";

SocketHelper server = new SocketHelper(prefix);

// 使用 CancellationTokenSource 来优雅地关闭 WebSocket 服务器
CancellationTokenSource cts = new CancellationTokenSource();

// 运行 WebSocket 服务器
Task serverTask = server.StartAsync(cts.Token);

_ = Task.Run(async () =>
{
    var oldTitle = "";

    while (true)
    {
        // 获取当前活动窗口信息
        var (title, processName, exePath) = WindowsHelper.GetActiveWindowInfoWithPath();

        if (oldTitle != title)
        {
            oldTitle = title;
            string base64String = "";
            Console.WriteLine($"当前活动窗口: {title} (进程: {processName})");

            // 获取高分辨率图标
            var icon = WindowsHelper.GetAppIcon(exePath);
            if (icon != null)
            {
                base64String = WindowsHelper.IconToBase64(icon); // PNG Base64
            }

            var json = new
            {
                type = 1,
                data = JsonConvert.SerializeObject(new
                {
                    mark = "当前活动窗口",
                    title = title,
                    icon = base64String
                })
            };
            await server.SendAllMessageAsync(json);
        }

        // 获取媒体播放信息（仅 Windows 10+）
        try
        {
            WindowsHelper.GetCurrentMediaInfo();
        }
        catch
        {
            // 忽略异常
        }

        Thread.Sleep(10000); // 每秒刷新一次
    }
});

// 等待用户按下 Enter 键来停止服务器
Console.WriteLine("Press Enter to stop the server...");
Console.ReadLine();

// 取消服务器任务
cts.Cancel();

// 等待服务器任务完成
await serverTask;

Console.WriteLine("Server has stopped.");

static bool IsRunAsAdministrator()
{
    // 判断程序是否以管理员身份运行
    var identity = WindowsIdentity.GetCurrent();
    var principal = new WindowsPrincipal(identity);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

static void RestartAsAdministrator()
{
    var startInfo = new ProcessStartInfo
    {
        FileName = "dotnet",
        Arguments = System.Reflection.Assembly.GetExecutingAssembly().Location,
        Verb = "runas",  // 使用管理员权限启动
        UseShellExecute = true
    };
    try
    {
        Process.Start(startInfo);
    }
    catch (Win32Exception ex) // 捕获权限错误
    {
        Console.WriteLine($"权限错误: {ex.Message}");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"无法以管理员身份启动程序: {ex.Message}");
    }
}

